package com.Interface.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


/** 
* HTTP工具箱 
* 
* 
*/ 
public final class HttpTookit { 

        /** 
         * 执行一个HTTP GET请求，返回请求响应的HTML 
         * 
         * @param url                 请求的URL地址 
         * @param queryString 请求的查询参数,可以为null 
         * @param charset         字符集 
         * @param pretty            是否美化 
         * @return 返回请求响应的HTML 
         */ 
        public static String doGet(String url, String queryString, String charset, boolean pretty) { 
                StringBuffer response = new StringBuffer(); 
                HttpClient client = new HttpClient(); 
                HttpMethod method = new GetMethod(url); 
                try { 
                        if (queryString.isEmpty()) 
                                //对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成为%式样的字符串 
                                method.setQueryString(URIUtil.encodeQuery(queryString)); 
                        client.executeMethod(method); 
                        if (method.getStatusCode() == HttpStatus.SC_OK) { 
                                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                                String line; 
                                while ((line = reader.readLine()) != null) { 
                                        if (pretty) 
                                                response.append(line).append(System.getProperty("line.separator"));
                                        else 
                                                response.append(line); 
                                } 
                                reader.close(); 
                        } 
                } catch (URIException e) { 
                    //    log.error("执行HTTP Get请求时，编码查询字符串“" + queryString + "”发生异常！", e); 
                } catch (IOException e) { 
                     //   log.error("执行HTTP Get请求" + url + "时，发生异常！", e); 
                } finally { 
                        method.releaseConnection(); 
                } 
                return response.toString(); 
        } 

        /** 
         * 执行一个HTTP POST请求，返回请求响应的HTML 
         * 
         * @param url         请求的URL地址 
         * @param params    请求的查询参数,可以为null 
         * @param charset 字符集 
         * @param pretty    是否美化 
         * @return 返回请求响应的HTML 
         */ 
        public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {

            StringBuffer response = new StringBuffer(); 
            HttpClient client = new HttpClient(); 
            PostMethod method = new PostMethod(url); 
            //设置Http Post数据 
            if (params != null) { 
                    for (Map.Entry<String, String> entry : params.entrySet()) { 
								method.setParameter(entry.getKey(),entry.getValue());
                    } 
                    
            } 
            try { 
            	    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                    client.executeMethod(method); 
                    if (method.getStatusCode() == HttpStatus.SC_OK) { 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                            String line; 
                            while ((line = reader.readLine()) != null) { 
                                    if (pretty) 
                                            response.append(line).append(System.getProperty("line.separator"));
                                    else 
                                            response.append(line); 
                            } 
                            reader.close(); 
                    } 
            } catch (IOException e) { 
                  //  log.error("执行HTTP Post请求" + url + "时，发生异常！", e); 
            } finally { 
                    method.releaseConnection(); 
            } 
            return response.toString(); 
    } 
        
    	public static String doHttpPost(String uri, String queryString,String ecode)
			throws ServletException, IOException {
		URL url = null;
		HttpURLConnection httpConn = null;
		OutputStream output = null;
		OutputStreamWriter outr = null;

		url = new URL(uri);
		httpConn = (HttpURLConnection) url.openConnection();
		HttpURLConnection.setFollowRedirects(true);
		httpConn.setDoOutput(true);
		httpConn.setRequestMethod("POST");
		// httpConn.setRequestProperty("Content-Type",
		// "text/plain; charset=utf-8");
		// httpConn.setRequestProperty("Content-Type",
		// "application/octet-stream");
		// httpConn.setRequestProperty("Accept-Charset", "gb2312");
		// httpConn.setRequestProperty("contentType", "gb2312");
		httpConn.connect();
		output = httpConn.getOutputStream();
		outr = new OutputStreamWriter(output,ecode);
		// 写入请求参数
		outr.write(queryString.toCharArray(), 0, queryString.length());
		outr.flush();
		outr.close();
		int code = httpConn.getResponseCode();
		// 读取响应内容
		String sCurrentLine = "";
		String sTotalString = "";
		if (code == 200) {
			java.io.InputStream is = httpConn.getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is,ecode));
			
//			 BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "GBK"));  
			while ((sCurrentLine = reader.readLine()) != null)
				if (sCurrentLine.length() > 0)
					sTotalString = sTotalString + sCurrentLine.trim();
		} else {
			sTotalString = "远程服务器连接失败,错误代码:" + code;

		}
		return sTotalString;
	}
        

	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		/*Token t = new Token();
		t.getToken();
		t.getCompanyId();*/
//	    String y = doGet("http://117.25.128.177:48004/UITSign/data/adduser?token=d5946aafafadec463069f8c9ebab8f29&companyId=22&phone=18046056247&password=123456&name=%e9%83%91%e4%b9%94&birthday=20000101&identify=1453&sex=0", null, "utf-8", true);
//		System.out.println(y);
		//nodetectface
		/*Map m=new HashMap();
		String p="{\"identify\":\"11\",\"imgPath\":\"http://117.25.128.117:48004/UITImg/18905900987/user_face_20160830_112434.jpg\"," +
				"\"name\":\"小葛\",\"headerId\":\"32\",\"uploadTime\":\"2016-08-30 11:24:34\"}";
		m.put("data",p);
		m.put("token", "07585f4821186f89e9df9aa9866d9ef5");
		String a=doPost("http://127.0.0.1:8080/ccms-ic/FaceSign/nodetectface.do",m,"utf-8",true);
		System.out.println(a);*/
		//usersign
		
		Map m=new HashMap();
		
		List<Map> list=new ArrayList<Map>();
		
		Map<String,Object> map=new HashMap<String, Object>();

		m.put("Token", "1");
		String p="{ACTUAL_TOTAL=3, VMC_NO=59201043, TOTAL=3, TRANSACTION=[{'OrderProducts':[{'Cab':'1','productNo':'can100701','productIntegre':0,'opID':5261,'Promotion_Price':0,'orderID':5263,'Preferential_Price':0,'discountPrice':0,'firstpurchaseprice':0,'productID':179,'Payment':null,'productType':null,'IntegreAmount':0,'PATH_NO':'41','moneyAmount':3,'Product_Images':'/junpeng_yiqi_attach/2017/7/10/83ab8819-9e2f-418d-98da-bae9d9149a49.jpg','customerPrice':0,'actualQuantity':1,'quantity':1,'productPrice':3,'productName':'可口可乐330ml'}],'OrderPay':{'REFUND_NON_CASH_AMOUNT':0,'AMOUNT_OWED':0,'COIN_AMOUNT':0,'REFUND_NOTE_AMOUNT':0,'realCoins':0,'payTime':'2017-07-28T00:16:09.877','REFUND_COIN_AMOUNT':0,'realNote':0,'shouldPay':3,'smallNote':0,'payID':5263,'CASH_AMOUNT':0,'realPay':3,'payDesc':'[SUCCESS](weixin://wxpay/bizpayurl?pr=LP6W1CH)','smallChange':0,'RefundAmount':0,'NON_CASH_AMOUNT':0,'orderID':5263,'integre':0,'Status':null,'NOTE_AMOUNT':0,'payStatus':2,'payType':4,'smallConis':0,'REFUND_CASH_AMOUNT':0},'Order':{'insurance':null,'customerName':null,'orderID':5263,'orderDesc':null,'orderType':0,'areaCode':null,'lastUpdateTime':'2017-07-28T00:16:20.61','integre':null,'proCode':null,'cityCode':null,'sendStatus':1,'consName':null,'orderTime':'2017-07-28T00:16:09.843','orderStatus':2,'addressDetail':null,'totalPay':3,'shouldPay':3,'shipType':0,'orderNo':'17072800160959201043263','productCount':1,'address':null,'consTel':null,'isNoFreight':null,'freight':null,'consPost':null,'shipTime':'2017-07-28T00:16:26.14'},'OrderRefund':null},{'OrderProducts':[{'Cab':'1','productNo':'can100902','productIntegre':0,'opID':5262,'Promotion_Price':0,'orderID':5264,'Preferential_Price':0,'discountPrice':0,'firstpurchaseprice':0,'productID':181,'Payment':null,'productType':null,'IntegreAmount':0,'PATH_NO':'45','moneyAmount':3,'Product_Images':'/junpeng_yiqi_attach/2017/7/10/3bafac0a-9825-4ec3-81db-876b10c852cd.jpg','customerPrice':0,'actualQuantity':1,'quantity':1,'productPrice':3,'productName':'百事可乐330ml'}],'OrderPay':{'REFUND_NON_CASH_AMOUNT':0,'AMOUNT_OWED':0,'COIN_AMOUNT':0,'REFUND_NOTE_AMOUNT':0,'realCoins':0,'payTime':'2017-07-28T00:21:12.36','REFUND_COIN_AMOUNT':0,'realNote':0,'shouldPay':3,'smallNote':0,'payID':5264,'CASH_AMOUNT':0,'realPay':3,'payDesc':'[SUCCESS](weixin://wxpay/bizpayurl?pr=iAEdCZd)','smallChange':0,'RefundAmount':0,'NON_CASH_AMOUNT':0,'orderID':5264,'integre':0,'Status':null,'NOTE_AMOUNT':0,'payStatus':2,'payType':4,'smallConis':0,'REFUND_CASH_AMOUNT':0},'Order':{'insurance':null,'customerName':null,'orderID':5264,'orderDesc':null,'orderType':0,'areaCode':null,'lastUpdateTime':'2017-07-28T00:21:27.327','integre':null,'proCode':null,'cityCode':null,'sendStatus':1,'consName':null,'orderTime':'2017-07-28T00:21:12.313','orderStatus':2,'addressDetail':null,'totalPay':3,'shouldPay':3,'shipType':0,'orderNo':'17072800211259201043264','productCount':1,'address':null,'consTel':null,'isNoFreight':null,'freight':null,'consPost':null,'shipTime':'2017-07-28T00:21:32.843'},'OrderRefund':null},{'OrderProducts':[{'Cab':'1','productNo':'can100902','productIntegre':0,'opID':5263,'Promotion_Price':0,'orderID':5265,'Preferential_Price':0,'discountPrice':0,'firstpurchaseprice':0,'productID':181,'Payment':null,'productType':null,'IntegreAmount':0,'PATH_NO':'45','moneyAmount':3,'Product_Images':'/junpeng_yiqi_attach/2017/7/10/3bafac0a-9825-4ec3-81db-876b10c852cd.jpg','customerPrice':0,'actualQuantity':1,'quantity':1,'productPrice':3,'productName':'百事可乐330ml'}],'OrderPay':{'REFUND_NON_CASH_AMOUNT':0,'AMOUNT_OWED':0,'COIN_AMOUNT':0,'REFUND_NOTE_AMOUNT':0,'realCoins':0,'payTime':'2017-07-28T00:21:41.407','REFUND_COIN_AMOUNT':0,'realNote':0,'shouldPay':3,'smallNote':0,'payID':5265,'CASH_AMOUNT':0,'realPay':3,'payDesc':'[SUCCESS](weixin://wxpay/bizpayurl?pr=1eSvsUO)','smallChange':0,'RefundAmount':0,'NON_CASH_AMOUNT':0,'orderID':5265,'integre':0,'Status':null,'NOTE_AMOUNT':0,'payStatus':2,'payType':4,'smallConis':0,'REFUND_CASH_AMOUNT':0},'Order':{'insurance':null,'customerName':null,'orderID':5265,'orderDesc':null,'orderType':0,'areaCode':null,'lastUpdateTime':'2017-07-28T00:21:52.313','integre':null,'proCode':null,'cityCode':null,'sendStatus':1,'consName':null,'orderTime':'2017-07-28T00:21:41.377','orderStatus':2,'addressDetail':null,'totalPay':3,'shouldPay':3,'shipType':0,'orderNo':'17072800214159201043265','productCount':1,'address':null,'consTel':null,'isNoFreight':null,'freight':null,'consPost':null,'shipTime':'2017-07-28T00:21:57.89'},'OrderRefund':null}]}";
		m.put("param", p);
		//http://127.0.0.1:8080/ccms-ic/FaceSign/nodetectface.do
		//http://59.60.28.232:9102/ccms-ic/FaceSign/usersign.do
		String a=doPost("http://127.0.0.1:8087/shj/api/vmcTransactionRecords.do",m,"utf-8",true);
		System.out.println(a);
		//test
//		Map m=new HashMap();
//		m.put("token","276aaba89bdb07d7fd11fc5c0dc1f957");
//		m.put("companyId", "2");
//		m.put("phone", "18046056247");
//		m.put("password", "password");
//		m.put("name", "%e9%83%91%e4%b9%94");
//		m.put("birthday", "20000101");
//		m.put("identify", "1453");
//		m.put("sex", "0");
//		String a=doPost("http://59.60.28.232:8010/yk/data/adduser?",m,"utf-8",true);
//		System.out.println(a);
/*		Map m=new HashMap();
		m.put("token","6e0549914761f65d63b377524efafff9");
		m.put("phone", "13338425804");
		m.put("password", "123456");
		m.put("name", "郑乔");
		m.put("birthday", "20000102");
		m.put("identify", "1453");
		m.put("sex", "0");
		String a=doPost("http://59.60.28.232:8010/yk/data/updateuser?",m,"utf-8",true);
		System.out.println(a);*/
		
		
		//
//		SignUtil  rsa = new SignUtil();
//		String modulus="BF2CCC08DB3DE0A9A2CCC92BBEBA058560272D62E0BA239D9CCD405CA4A058604ABCC3137BAF1F92AD73B764DD91FC50140D3877E2C3563173CD19AA3B62BFCA50262F7891B7503BBED3B88AB8BEA07481B95B939B08DA34C65DFC6AE45F01D809580785179BF777502EC79C318615E24188341D0CD05B827415D6947794048D";
//		String privateExponet="0E9811DF5F354310502047FF31E92B80BA0D639697C73DEECB4893F03E950B0A16CA802DDD9449D9BDAA06C7096F1A8ED66907F586F7187E5FF3B950D885BA544A9426151BDA3B91D7AB6AA2074404BFDCF5F837CCFF614C3221020DA0D6E55E7B3DEB2A3011AA003A1D7466026A7ECB05EE1951ABFBDA75EA444F451C5A2F01";
//		//得到私钥
//		String data="<?xml version=\"1.0\" encoding=\"UTF-8\"?><TcpCont><TransactionID>600105A002201203150000000054</TransactionID><ActionCode>0</ActionCode><BusCode>FJBUS300</BusCode><ServiceCode>FJSVC203</ServiceCode><ServiceContractVer>FJSVC20320120315</ServiceContractVer><ServiceLevel>1</ServiceLevel><SrcOrgID>600105</SrcOrgID><SrcSysID>600105A091</SrcSysID><SrcSysSign/><DstOrgID>600105</DstOrgID><DstSysID>6001050001</DstSysID><ReqTime>20120315000000</ReqTime></TcpCont><SvcCont><!--dddddd--><SOO type="+"\"QRY_PROD_OFFER_INST_REQ_TYPE"+"\"><PUB_REQ><SOO_ID>1</SOO_ID></PUB_REQ><QRY_REQ><FIELD>PROD_OFFER_INST_ID</FIELD><FIELD>PARENT_OFFER_PROD_INST_ID</FIELD><FIELD>PROD_OFFER_NAME</FIELD><FIELD>EXT_PROD_OFFER_CODE</FIELD></QRY_REQ><PROD_INST_ID>:getCrmProdInstIdByAccNbr(0591,18059040470,610003886)</PROD_INST_ID></SOO></SvcCont></ContractRoot>";
////		String data="<area_code></area_code><acc_nbr>18950295930</acc_nbr><billing_cycle_id>201606</billing_cycle_id><mdse_type>3</mdse_type>";
//		System.out.println(data);
//		PrivateKey privateKey;
//		String respDate ="";
//		try {
//			privateKey = rsa.getPrivateKey(modulus, privateExponet);
//			respDate= rsa.sign(data.getBytes(), privateKey);
//			System.out.println(">>>>"+respDate);
//		} catch (Exception e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		//获取签名
////	6CCC96A6E483841B9833B4F6AB99844796AF764F23FCC2F9D17955762E6DEE23364607AD7FA6196FEE964D90B3A9F14EF25EAFEC26DCBE8E921441C6955C1D0BC95540A1B3BBCAE39FD316859DE4A776136E7ED3878AE2BD7ABF5592FA3C0B6A17EC30C64C37B1BA5D5D8CDE4D9742E9CDBB0C348245585712371AD66C69A2F2
////		respDate="41E998AB8F8DAAA0FB84C425395A7D1CDC6DB1BF707F1057DA1790F20FFB4974AFB4DE692E1B2FDED6155D6BD0164F8E8A7CF1FEE34C4687E0DD14E9963A6B482AF6E9E360EA79D1BDA60968581F961AF10C6EAFE90926F3DCD5B47F150D9DB5FC5F035094381A43CDBC89FD9BC9EBC58B6F056936E6732886227D84A79BCE10";
//		StringBuffer sql=new StringBuffer();
//    	sql.append("<arg1><intfname>simple_ratable_query</intfname>");
//    	sql.append("<user>ceshi_user</user>");
//    	sql.append("<passwd>123456</passwd><sign_result>"+respDate+"</sign_result></arg1>");
//     	sql.append("<simple_ratable_query_in><area_code></area_code><acc_nbr>18950295930</acc_nbr><billing_cycle_id>201606</billing_cycle_id><mdse_type>3</mdse_type></simple_ratable_query_in>");
////     	sql.append("<user>ceshi_user</user>");
////            String y = doGet("http://localhost:8080/fisp/sms/send.api", sql.toString(), "UTF-8", true); 
////            System.out.println(y); 
//
//		try {
//			String a=doHttpPost("http://218.85.155.59:8751/simple_ratable_query",sql.toString(),"GBK");
//			
//			System.out.println("a>>>>"+a);
//			String json=XmlConverUtil.xmltoJson(a);
//			System.out.println(">>>>"+json);
//		} catch (ServletException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			System.out.println("111");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			System.out.println("11122");
//		}
		
//		String data="{\"CmdType\":\"903\",\"Session\":\"1466758873\" ,\"TerminalFlag\":\"\",\"TerminalType\":\"\" ,\"Sequence\":\"1\" ,\"Timestamp\":\"1456277923\" ,\"SubCmd\":\"011\" ,\"Body\":{\"ID\":\"1\",\"Object\":\"3\",\"ObjectString\":\"3501\",\"MessageType\":\"1\",\"Action\":\"01\",\"Title\":\"你好\",\"Content\":\"\u5927\u5bb6\u597d\",\"Url\":\"\"} }";
//		try {
//			String a=doHttpPost("http://110.84.128.190:16904/10000Service",data,"GBK");
//		} catch (ServletException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}String url, Map<String, String> params, String charset, boolean pretty
		
		
		

	} 
}